package com.usiful.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.usiful.model.ActionArg;
import com.usiful.utils.FileUtil;
import com.usiful.utils.PathUtil;
import com.usiful.utils.PropertiesUtil;
import com.usiful.utils.ShellUtil;

/**
 * 构建控制器,目前仅支持gradle构建
 * 
 * @author [周织能]
 *
 */
public class BuildController extends BaseController {

	public final static String ACTION_GRADLE = "gradle";
	public final static String ACTION_ANT = "ant";

	public final static String ARG_SDK_PATH = "sdkpath";
	public final static String ARG_PROJECT_PATH = "path";

	protected String mProjectPath;
	protected String mSdkPath;
	
	@Override
	public boolean handleAction(ActionArg arg) {
		// TODO Auto-generated method stub
		super.handleAction(arg);
		mProjectPath = arg.getArgValueMap().get(ARG_PROJECT_PATH).get(0);
		mSdkPath = arg.getArgValueMap().get(ARG_SDK_PATH).get(0);
		try {
			prepEnv();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println(e.getMessage());
			System.exit(1);
		}
		if (clean()) {
			return build();
		} else {
			return false;
		}
	}

	public BuildController() {

	}

	
	/**
	 * 设置环境
	 * @throws Exception 
	 */
	private void prepEnv() throws Exception {
		// String sdkDir = "/Users/zhouzhineng/Downloads/adt-bundle-mac-x86_64-20140702/sdk/";
		//File dir = new File("");
		//String confFilePath = PathUtil.getFullPath(dir.getAbsolutePath(), "conf", "global.properties");
		/*String confFilePath = PathUtil.getFullPath(mProjectPath, "local.properties");
		PropertiesUtil prop = PropertiesUtil.getInstance(confFilePath);
		String sdkDir = prop.get("sdk.dir");
		if (sdkDir == null || sdkDir.length() == 0) {
			throw new Exception("you must set android sdk path!");
		}*/
		//String wrapperDir = PathUtil.getFullPath(sdkDir, "tools", "templates", "gradle", "wrapper");
		String wrapperDir = PathUtil.getFullPath(mSdkPath, "tools", "templates", "gradle", "wrapper");
		if (System.getProperties().getProperty("os.name").toUpperCase().indexOf("WINDOWS") != -1) {
			FileUtil.copyFile(PathUtil.getFullPath(wrapperDir, "gradlew.bat"),
					PathUtil.getFullPath(mProjectPath, "gradlew.bat"));
		} else {
			FileUtil.copyFile(PathUtil.getFullPath(wrapperDir, "gradlew"),
					PathUtil.getFullPath(mProjectPath, "gradlew"));
		}
		FileUtil.deleteFolder(PathUtil.getFullPath(mProjectPath, "gradle", "wrapper"));
		FileUtil.mkdir(PathUtil.getFullPath(mProjectPath, "gradle"));
		FileUtil.copyFolder(PathUtil.getFullPath(wrapperDir, "gradle", "wrapper"),
				PathUtil.getFullPath(mProjectPath, "gradle","wrapper"));
	}

	private boolean build() {
		boolean cmdExecState = true;
		String cmd = "";
		if (System.getProperties().getProperty("os.name").toUpperCase().indexOf("WINDOWS") != -1) {
			cmd = PathUtil.getFullPath(mProjectPath, "gradlew.bat");
		} else {
			cmd = PathUtil.getFullPath(mProjectPath, "gradlew");
		}
		String[] args = { "build", "-b", PathUtil.getFullPath(mProjectPath, "build.gradle") };
		try {
			ShellUtil.ShellCmdResult cmdResult = ShellUtil.exec(cmd, args);
			if (cmdResult.errcode == ShellUtil.SHELL_EXEC_SUCC) {
				cmdExecState = true;
				System.out.println("执行成功!");
			} else {
				cmdExecState = false;
				System.out.println("执行失败:" + cmdResult.desc);
			}
		} catch (Exception e) {
			cmdExecState = false;
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return cmdExecState;

	}

	private boolean clean() {
		boolean cmdExecState = true;
		String wrapper = "";
		//wrapper = PathUtil.getFullPath(mProjectPath, "gradlew");
		if (System.getProperties().getProperty("os.name").toUpperCase().indexOf("WINDOWS") != -1) {
			wrapper = PathUtil.getFullPath(mProjectPath, "gradlew.bat");
		} else {
			wrapper = PathUtil.getFullPath(mProjectPath, "gradlew");
		}
		String[] lintSteps = { "lint", "compileLint" };
		List<String> args = new ArrayList<>();
		args.add("clean");
		args.add("-b");
		args.add(PathUtil.getFullPath(mProjectPath, "build.gradle"));

		// 10 seconds -> 6 seconds
		args.add("-Dorg.gradle.daemon=true");
		// Excluding lint: 6s-> 1.6s

		for (int i = 0; i < lintSteps.length; ++i) {
			args.add("-x " + lintSteps[i]);
		}
		try {
			cmdExecState = ShellUtil.exec(wrapper,
					(String[]) args.toArray(new String[args.size()])).errcode == ShellUtil.SHELL_EXEC_SUCC ? true
							: false;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			cmdExecState = false;
			e.printStackTrace();
		}
		return cmdExecState;
	}
}
